import React, {PureComponent} from "react"
import {DragSource, DropTarget } from "react-dnd"
import ItemType from "./itemType"
import "./styles.less"

const dragSource = {
  beginDrag(props) {
    return props.data
  },
  endDrag(props) {
    if (props.onEndDrag)props.onEndDrag(props.data)
  }
}

const dropTarget = {
  hover(props, monitor) {
    const source = monitor.getItem()
    const target = props.data
    if (props.onHover)props.onHover(source, target)
  },
}


@DropTarget(ItemType.ITEM, dropTarget, connect => ({
  connectDropTarget: connect.dropTarget(),
}))
@DragSource(ItemType.ITEM, dragSource, (connect, monitor) => ({
  connectDragSource: connect.dragSource(),
  isDragging: monitor.isDragging(),
}))
class Item extends PureComponent {

  onClick = () => {
    if (this.props.onItemClick) this.props.onItemClick(this.props.data)
  }

  render() {
    const {connectDragSource, connectDropTarget, isDragging, className} = this.props
    return connectDragSource(connectDropTarget(
      <li className={ `drag-list-item ${className} ${isDragging ? "dragging" : ""}` } onClick={ this.onClick }>
        { this.props.children }
      </li>
    ))
  }
}

export default Item


